<script setup>
import { ref } from 'vue'
import { userpasswordUpService } from '@/api/user/userinfo'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const id = ref(userStore.user.id)
import { useRouter } from 'vue-router'

const formRef = ref()
const pwdForm = ref({
  new_pwd: '',
  re_pwd: ''
})

const checkSameAsNewPwd = (rule, value, callback) => {
  // 校验确认密码必须和新密码一样
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('确认密码必须和新密码一样'))
  } else {
    callback()
  }
}
const rules = ref({
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '原密码长度在6-20位之间', trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '确认密码长度在6-20位之间', trigger: 'blur' },
    { validator: checkSameAsNewPwd, trigger: 'blur' }
  ]
})

const router = useRouter()

const submitForm = async () => {
  await formRef.value.validate()
  userpasswordUpService({
    id: id.value,
    password: pwdForm.value.new_pwd,
    tar: '1'
  })
    .then((response) => {
      if (response.data.status == 200) {
        ElMessage.success(response.data.message)
      } else {
        ElMessage.error(response.data.message)
      }
    })
    .catch((error) => {
      ElMessage.error(error)
    })

  // 密码修改成功后，退出重新登录
  // 清空本地存储的 token 和 个人信息
  userStore.setToken('')
  userStore.setUser({})

  // 拦截登录
  router.push('/')
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="修改密码">
    <el-row>
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="pwdForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="pwdForm.new_pwd" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input v-model="pwdForm.re_pwd" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">修改密码</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form></el-col
      >
    </el-row>
  </page-container>
</template>
